import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCount {
    public static void main(String[] args) throws Exception {
        // 设置执行环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 输入数据 - 可以从文件、Kafka等来源读取，这里使用静态数据作为示例
        DataStream<String> text = env.fromElements(
                "Hello Flink",
                "Hello World",
                "Flink is cool",
                "Java and Flink",
                "Hello Java"
        );

        // 执行计算: 分割单词并统计
        DataStream<Tuple2<String, Integer>> counts = text
                // 分割句子为单词
                .flatMap(new Tokenizer())
                // 按单词分组
                .keyBy(value -> value.f0)
                // 累加计数
                .sum(1);

        // 输出结果
        counts.print();

        // 执行任务
        env.execute("Flink test.WordCount Demo");
    }

    // 自定义分词器
    public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
            // 分割句子为单词
            String[] words = value.toLowerCase().split("\\W+");

            // 发射每个单词，计数为1
            for (String word : words) {
                if (word.length() > 0) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        }
    }
}
    